package org.rendao.question.edit
{
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import org.rendao.entity.FirstIndex;
	import org.rendao.entity.Question;
	import org.rendao.entity.SecondIndex;
	import org.rendao.entity.UserDetail;
	import org.rendao.service.FirstIndexService;
	import org.rendao.service.QuestionService;
	import org.rendao.service.SecondIndexService;
	import org.rendao.service.UserService;

	public class QuestionEditViewPM
	{
		public var dm:QuestionEditViewDM;
		
		public function getFirstIndexList():void {
			var onGet:Function = function(list:Array):void {
				var result:ArrayCollection = new ArrayCollection(list);
				dm.firstIndexList = result;
				if(list.length > 0) {
					var firstIndexId:String = (list[0] as FirstIndex).id;
					getSecondIndexList(firstIndexId);
				}
				else {
					dm.secondIndexList = new ArrayCollection();
				}
			};
			FirstIndexService.instance.getAll(onGet);
		}
		
		public function getSecondIndexList(firstIndexId:String, callback:Function=null):void {
			var onGet:Function = function(list:Array):void {
				var result:ArrayCollection = new ArrayCollection(list);
				dm.secondIndexList = result;
				if(callback != null) {
					callback();
				}
			};
			SecondIndexService.instance.getByFirstIndex(firstIndexId, onGet);
		}
		
		public function getUserList():void {
			var onGet:Function = function(list:Array):void {
				var result:ArrayCollection = new ArrayCollection(list);
				dm.userList = result;
			};
			UserService.instance.getAllUser(onGet);
		}
		
		public function getFirstIndexSelectedIndex(firstIndexId:String):int {
			if(!dm.firstIndexList || dm.firstIndexList.length == 0) {
				return -1;
			}
			for(var i:int=0; i<dm.firstIndexList.length; i++) {
				var id:String = (dm.firstIndexList.getItemAt(i) as FirstIndex).id;
				if(firstIndexId == id) {
					return i;
				}
			}
			return -1;
		}
		
		public function getSecondIndexSelectedIndex(secondIndexId:String):int {
			if(!dm.secondIndexList || dm.secondIndexList.length == 0) {
				return -1;
			}
			for(var i:int=0; i<dm.secondIndexList.length; i++) {
				var id:String = (dm.secondIndexList.getItemAt(i) as SecondIndex).id;
				if(secondIndexId == id) {
					return i;
				}
			}
			return -1;
		}
		
		public function getUserSelectedIndex(userId:String):int {
			if(!dm.userList || dm.userList.length == 0) {
				return -1;
			}
			for(var i:int=0; i<dm.userList.length; i++) {
				var id:String = (dm.userList.getItemAt(i) as UserDetail).id;
				if(userId == id) {
					return i;
				}
			}
			return -1;
		}
		
		public function saveQuestion(question:Question):void {
			var onSave:Function = function(result:Question):void {
				dm.question = result;
				Alert.show("保存成功");
			};
			QuestionService.instance.save(question, onSave);
		}
		
		public function deleteQuestion():void {
		}
	}
}